package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.WebLoginBody;
import com.ruoyi.common.core.domain.model.WxDecPhone;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.WebTokenService;
import com.ruoyi.system.domain.DzDeptsync;
import com.ruoyi.system.domain.DzHuiyuan;
import com.ruoyi.system.domain.DzUsersync;
import com.ruoyi.system.domain.vo.AuthLogin;
import com.ruoyi.system.domain.vo.AuthUser;
import com.ruoyi.system.service.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class WebLoginController
{
    @Autowired
    private WebTokenService tokenService;

    @Autowired
    private IDzHuiyuanService dzHuiyuanService;

    @Autowired
    private IDzUsersyncService dzUsersyncService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IDzDeptsyncService dzDeptsyncService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IDzHuiyuanService zzHuiyuanService;
    // 小程序appid
    private String APP_ID="wxe1618efed27fb8d3";
    // 小程序的app secret
    private String APPSECRET="02d0fe578f5bab5ab28f6a96f905cf35";

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/weblogin")
    public AjaxResult login(@RequestBody WebLoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
//        String loginpass = SecurityUtils.encryptPassword(loginBody.getPassword());
        String loginpass = loginBody.getPassword();
        DzHuiyuan dzHuiyuan = new DzHuiyuan();
        dzHuiyuan.setLoginname(loginBody.getLoginname());
        dzHuiyuan.setPassword(loginpass);
        System.out.println("@@@@####:"+dzHuiyuan.getLoginname());
        List<DzHuiyuan> list = dzHuiyuanService.selectDzHuiyuanWebList(dzHuiyuan);
        if(list!=null&&list.size()>0){
            DzHuiyuan dzHuiyuan2 = list.get(0);
            if(SecurityUtils.matchesPassword(loginpass,dzHuiyuan2.getPassword())){
               String token =  tokenService.createToken(dzHuiyuan2);
               ajax.put(Constants.TOKEN, token);
               return ajax;

            }else{
                return AjaxResult.error(-2,"账号密码错误");
            }
        }else{
            return  AjaxResult.error(-1,"账号不存在，请先注册账号");
        }
    }



    @PostMapping("/authLogin")
    public AjaxResult authLogin(@RequestBody AuthLogin authLogin)
    {
        AjaxResult ajax = AjaxResult.success();
        String token = dzHuiyuanService.getAccessToken();
        String auth_code = authLogin.getTmp_auth_code();
        AuthUser authUser =  dzHuiyuanService.getAuthUser(token,auth_code);
       if(authUser.getUserCode()==null){
           return AjaxResult.error("授权码失效，请重新点击登录");
       }
        DzUsersync userinfo = dzHuiyuanService.getUserInfo(token,authUser.getUserCode());
        Long pid = 100l;
        //先处理用户组织同步
        if(userinfo!=null&&userinfo.getUserCode()!=null&&userinfo.getUserDepts()!=null){
            //获取用户所属部门
            DzDeptsync deptSync = userinfo.getUserDepts().get(0);
            if(deptSync!=null){
                //遍历当前用户所属部门的部门路径
                String deptStr[]= deptSync.getUnitPath().split("/");
                for(String unitcode:deptStr){
                    if(unitcode!=null&&!"".equals(unitcode)&&!"-1".equals(unitcode)){
                        //从接口获取部门信息
                        DzDeptsync deptinfo = dzHuiyuanService.getZuzhi(token,unitcode);
                        if(deptinfo!=null){
                            //查看当前部门有没有同步过
                            DzDeptsync dbdept = dzDeptsyncService.selectDzDeptsyncByCode(deptinfo.getUnitCode());
                            if(dbdept==null){
                                //如果没有同步过先在部门表中插入
                                SysDept sysDept = new SysDept();
                                sysDept.setDeptName(deptinfo.getUnitName());
                                sysDept.setOrderNum(Integer.parseInt(deptinfo.getUnitOrder()==null?"99":deptinfo.getUnitOrder()));
                                sysDept.setStatus("0");
                                sysDept.setParentId(pid);
                                if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(sysDept)))
                                {
                                    continue;
                                }
                                deptService.insertDept(sysDept);
                                //将上级id赋值，便于下一个部门插入的时候初始化父节点
                                pid = sysDept.getDeptId();
                                //插入部门同步表
                                deptinfo.setDeptId(sysDept.getDeptId());
                                dzDeptsyncService.insertDzDeptsync(deptinfo);
                            }else{
                                //如果同步过，将上次存放的部门id赋值给pid
                                pid=dbdept.getDeptId();
                            }
                        }
                    }
                }
            }
        }
//      如果是后台登录
        if(authLogin.getType()==1){
            DzUsersync query = new DzUsersync();
            query.setRegCellPhone(authUser.getRegCellPhone());
            List<DzUsersync> usersyncs =  dzUsersyncService.selectDzUsersyncListWeb(query);
            //如果平台用户已经存在，获取用户直接登录
            if(usersyncs!=null&&usersyncs.size()>0){
                //取出数据库中的平台用户
                DzUsersync dbuser = usersyncs.get(0);
                //如果是先PC登录，且用户角色是教师的时候，此时要同步一次管理用户
                if(dbuser.getUserId()==null&&"1".equals(dbuser.getType())){
                    SysUser inuser = new SysUser();
                    inuser.setDeptId(pid);
                    Long[] roleIds = new Long[]{101l};
                    inuser.setRoleIds(roleIds);
                    inuser.setDelFlag("0");
                    inuser.setNickName(dbuser.getUserName());
                    inuser.setUserName(dbuser.getUserName());
                    inuser.setPhonenumber(dbuser.getRegCellPhone());
                    inuser.setSex(dbuser.getSex());
                    inuser.setStatus("0");
                    inuser.setEmail(dbuser.getRegEmail());
                    inuser.setPassword(SecurityUtils.encryptPassword(dbuser.getUserCode()));
                    if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(inuser.getUserName())))
                    {
                        return AjaxResult.error("新增用户'" + inuser.getUserName() + "'失败，登录账号已存在");
                    }
                    else if (StringUtils.isNotEmpty(inuser.getPhonenumber())
                            && UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(inuser)))
                    {
                        return AjaxResult.error("新增用户'" + inuser.getUserName() + "'失败，手机号码已存在");
                    }
                    else if (StringUtils.isNotEmpty(inuser.getEmail())
                            && UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(inuser)))
                    {
                        return AjaxResult.error("新增用户'" + inuser.getUserName() + "'失败，邮箱账号已存在");
                    }
                    sysUserService.insertUser(inuser);
                    dbuser.setUserId(inuser.getUserId());
                    dzUsersyncService.updateDzUsersync(dbuser);
                }
                if(!"1".equals(dbuser.getType())){
                    return AjaxResult.error("非教职工用户，无法登录管理端");
                }
                ajax.put("user",userinfo);
            }else{//如果用户不存在，先获取平台用户，再将用户插入临时表
                SysUser inuser = new SysUser();
                inuser.setDeptId(pid);
                Long[] roleIds = new Long[]{101l};
                inuser.setRoleIds(roleIds);
                inuser.setDelFlag("0");
                inuser.setNickName(userinfo.getUserName());
                inuser.setUserName(userinfo.getUserName());
                inuser.setPhonenumber(userinfo.getRegCellPhone());
                inuser.setSex(userinfo.getSex());
                inuser.setStatus("0");
                inuser.setEmail(userinfo.getRegEmail());
                inuser.setPassword(SecurityUtils.encryptPassword(userinfo.getUserCode()));
                if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(inuser.getUserName())))
                {
                    return AjaxResult.error("新增用户'" + inuser.getUserName() + "'失败，登录账号已存在");
                }
                else if (StringUtils.isNotEmpty(inuser.getPhonenumber())
                        && UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(inuser)))
                {
                    return AjaxResult.error("新增用户'" + inuser.getUserName() + "'失败，手机号码已存在");
                }
                else if (StringUtils.isNotEmpty(inuser.getEmail())
                        && UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(inuser)))
                {
                    return AjaxResult.error("新增用户'" + inuser.getUserName() + "'失败，邮箱账号已存在");
                }
                sysUserService.insertUser(inuser);
                userinfo.setUserId(inuser.getUserId());
                dzUsersyncService.insertDzUsersync(userinfo);
                ajax.put("user",userinfo);
            }
        }else{

            DzUsersync query = new DzUsersync();
            query.setRegCellPhone(authUser.getRegCellPhone());
            List<DzUsersync> usersyncs =  dzUsersyncService.selectDzUsersyncListWeb(query);
            //如果平台用户已经存在，获取用户直接登录
            if(usersyncs!=null&&usersyncs.size()>0){
                //取出数据库中的平台用户
                DzUsersync dbuser = usersyncs.get(0);
                //如果是先后台登录，且用户角色是教师的时候，此时要同步一次管理用户
                if(dbuser.getHuiyuanId()==null){
                    DzHuiyuan huiyuan = new DzHuiyuan();
                    huiyuan.setLoginname(dbuser.getRegCellPhone());
                    huiyuan.setPassword(SecurityUtils.encryptPassword(dbuser.getUserCode()));
                    huiyuan.setUsername(dbuser.getUserName());
                    huiyuan.setSex(Long.parseLong(dbuser.getSex()));
                    huiyuan.setDn(dbuser.getRegCellPhone());
                    huiyuan.setUserType("2".equals(dbuser.getType())?0l:Long.parseLong(dbuser.getType()));
                    if(dbuser.getBirthday()!=null){
                        huiyuan.setBirthday(DateUtils.dateTime(DateUtils.YYYY_MM_DD,dbuser.getBirthday()));
                    }
                    huiyuan.setDeptId(pid);
                    huiyuan.setAddress(dbuser.getOfficeAddress());
                    huiyuan.setIdno(dbuser.getIdCardNo());
                    huiyuan.setJiguan(dbuser.getNativePlace());
                    dzHuiyuanService.insertDzHuiyuan(huiyuan);
                    dbuser.setHuiyuanId(huiyuan.getId());
                    dzUsersyncService.updateDzUsersync(dbuser);
                }
                ajax.put("user",userinfo);
            }else{//如果用户不存在，先获取平台用户，再将用户插入临时表
                DzHuiyuan huiyuan = new DzHuiyuan();
                huiyuan.setLoginname(userinfo.getRegCellPhone());
                huiyuan.setPassword(SecurityUtils.encryptPassword(userinfo.getUserCode()));
                huiyuan.setUsername(userinfo.getUserName());
                huiyuan.setSex(Long.parseLong(userinfo.getSex()));
                huiyuan.setDn(userinfo.getRegCellPhone());
                huiyuan.setUserType("2".equals(userinfo.getType())?0l:Long.parseLong(userinfo.getType()));

                if(userinfo.getBirthday()!=null){
                    huiyuan.setBirthday(DateUtils.dateTime(DateUtils.YYYY_MM_DD,userinfo.getBirthday()));
                }

                huiyuan.setDeptId(pid);
                huiyuan.setAddress(userinfo.getOfficeAddress());
                huiyuan.setIdno(userinfo.getIdCardNo());
                huiyuan.setJiguan(userinfo.getNativePlace());
                dzHuiyuanService.insertDzHuiyuan(huiyuan);
                userinfo.setHuiyuanId(huiyuan.getId());
                dzUsersyncService.insertDzUsersync(userinfo);
                ajax.put("user",userinfo);
            }

        }


        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getWebInfo")
    public AjaxResult getInfo(HttpServletRequest request)
    {
       DzHuiyuan huiyuan = tokenService.getDzHuiyuan(request);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", huiyuan);
        return ajax;
    }


    @PostMapping("getDeptUserInfo")
    public AjaxResult getDeptUserInfo(@RequestBody SysDept dept)
    {
        SysUser user =  sysUserService.selectUserByPhone(dept.getPhone());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        return ajax;
    }

    @PostMapping("/bind")
    public AjaxResult deciphering(@RequestBody WxDecPhone wxDecPhone) {
        String code = wxDecPhone.getCode();//code 为getPhoneNumber(e)后的e.detail.code
        String phone = "";
        String access_token = getAccess_token();
        System.out.println("code:" + code);
        System.out.println("access_token:" + access_token);

        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
        JSONObject body = new JSONObject();
        body.put("code", code);
        try {
            String ret = httpPostRaw(url, body.toString(), null, null);
            System.out.println("ret:" + ret);
            if(ret != null && !"".equals(ret)) {
                JSONObject json = JSONObject.parseObject(ret);
                JSONObject phone_info = json.getJSONObject("phone_info");
                phone = phone_info.getString("phoneNumber");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        DzHuiyuan huiyuan =  zzHuiyuanService.selectDzHuiyuanByDn(phone);
        if(huiyuan!=null){
            String token =  tokenService.createToken(huiyuan);
            huiyuan.setToken(token);
            AjaxResult ajax = AjaxResult.success(huiyuan);
            return ajax;
        }else{
            DzHuiyuan huiyuan1 = new DzHuiyuan();
            huiyuan1.setLoginname(phone);
            huiyuan1.setDn(phone);
            huiyuan1.setUserType(0l);
            huiyuan1.setUsername(phone);
            huiyuan1.setPassword(SecurityUtils.encryptPassword(phone));
            huiyuan1.setUserPic("/profile/upload/header.jpg");
            zzHuiyuanService.insertDzHuiyuan(huiyuan1);
            String token =  tokenService.createToken(huiyuan1);
            huiyuan1.setToken(token);
            AjaxResult ajax = AjaxResult.success(huiyuan1);
            return ajax;
        }




    }

    /**
     * 微信接口请求令牌：生产环境下 要用redis缓存起来
     * @return
     */
    public String getAccess_token() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + APP_ID + "&secret=" + APPSECRET;
        String accessToken = null;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = JSONObject.parseObject(message);
            accessToken = demoJson.getString("access_token");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    /**
     * 参数以raw的方式做post请求
     *
     * @param url
     * @param stringJson
     * @param headers
     * @param encode
     * @return
     */
    public static String httpPostRaw(String url, String stringJson, Map<String, String> headers, String encode) {
        String str = "";
        if (encode == null) {
            encode = "utf-8";
        }
        // HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost httpost = new HttpPost(url);

        // 设置header
        httpost.setHeader("Content-type", "application/json");
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // 组织请求参数
        StringEntity stringEntity = new StringEntity(stringJson, encode);
        httpost.setEntity(stringEntity);
        String content = null;
        CloseableHttpResponse httpResponse = null;
        try {
            // 响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
            System.out.println(content);
            str = content;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try { // 关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }



    public static String httpPost(String url, Map<String, String> params) throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);

        // 添加请求参数到请求对象
        List<BasicNameValuePair> parameters = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));

        // 发送请求并获取响应
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    }


    public static void main(String  args[]){
//
        String url = "https://116.62.48.140:7882/rtc/createRoom.htm";
        String str = null;
        Map<String, String> params = new HashMap<>();
        params.put("room_name","2223333");
        params.put("maxParticipants","100");
        params.put("emptyTimeout","7200");
//
//        String url = "http://116.62.48.140:7882/rtc/getToken.htm?name=&identity=&room_name=123";
//        String str = null;
//        Map<String, String> params = new HashMap<>();
//        params.put("name","zhangyang");
//        params.put("identity","zhangyang");
//        params.put("room_name","111222");
        try {
            str = httpPost(url,params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(str);



    }

}
